﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orchard.Events;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.DisplayManagement;

namespace Downplay.Audit.Rules
{
    public interface IFormProvider : IEventHandler
    {
        void Describe(dynamic context);
    }

    [OrchardFeature("Downplay.Audit.Rules")]
    public class AuditForms : IFormProvider
    {
        protected dynamic Shape { get; set; }
        public Localizer T { get; set; }

        public AuditForms(IShapeFactory shapeFactory)
        {
            Shape = shapeFactory;

            T = NullLocalizer.Instance;
        }

        public void Describe(dynamic context)
        {
            Func<IShapeFactory, dynamic> form =
                shape => Shape.Form(
                Id: "ActionAudit",
                _AuditCode: Shape.Textbox(
                    Id: "AuditCode", Name: "AuditCode",
                    Title: T("Audit Code"),
                    Description: T("A unique identifier code for the type of audit."),
                    Classes: new[] { "text" }),
                _AuditData: Shape.Textarea(
                    Id: "AuditData", Name: "AuditData",
                    Title: T("Audit Data"),
                    Description: T("Any supplemental data you wish to store with the audit record. You can use any tokens provided by the event."),
                    Classes: new[] { "tokenized" })
                );

            context.Form("ActionAudit", form);
        }
    }

    public interface IFormEventHandler : IEventHandler {
        void Validating(dynamic context);
    }

    public class AuditFormsValidator : IFormEventHandler
    {
        public Localizer T { get; set; }

        public AuditFormsValidator()
        {
            T = NullLocalizer.Instance;
        }

        public void Validating(dynamic context)
        {
            if (context.FormName == "ActionAudit")
            {
                string code = context.ValueProdiver.GetValue("AuditCode").AttemptedValue;
                if (String.IsNullOrWhiteSpace(code)) {
                    context.ModelState.AddModelError("AuditCode", T("You must enter an Audit Code to identify this audit event").Text);
                }
                else if (code.Length > 31)
                {
                    context.ModelState.AddModelError("AuditCode", T("Audit Code must be no more than 31 characters").Text);
                }
            }
        }
    }
}
